/**
 * 服务层主入口文件
 * 统一导出所有服务类和工具
 */

// 基础服务
export { default as BaseService } from './baseService';
export type { ApiResponse, PaginatedResponse, ApiError } from './baseService';

// 商品服务
export { default as ProductService, productService } from './productService';

// 搜索服务
export { default as SearchService, searchService } from './searchService';

// 分类服务
export { default as CategoryService, categoryService } from './categoryService';

// 错误处理
export { default as ErrorHandler, errorHandler } from './errorHandler';
export type { AppError, ErrorType } from './errorHandler';

// 拦截器
export { default as InterceptorManager, interceptorManager } from './interceptors';
export type { RequestInterceptor, ResponseInterceptor, InterceptorConfig } from './interceptors';

// 配置管理
export { default as ApiConfigManager, apiConfigManager, apiServiceFactory } from './apiConfig';
export type { Environment, ApiConfig, ApiEndpoints } from './apiConfig';

// Mock数据生成器
export { default as MockDataGenerator, mockDataGenerator } from './mockDataGenerator';
export type { MockDataConfig } from './mockDataGenerator';

/**
 * 服务初始化函数
 */
export function initializeServices(): void {
  // 导入服务实例
  import('./apiConfig').then(({ apiConfigManager, apiServiceFactory }) => {
    // 配置API服务
    apiServiceFactory.configureAllServices();
    
    // 开发环境日志
    if (process.env.NODE_ENV === 'development') {
      console.log('🚀 [Services] 服务层初始化完成');
      
      // 输出配置信息
      const config = apiConfigManager.exportForDebug();
      console.log('⚙️ [Services] 当前配置:', config);
    }
  }).catch(error => {
    console.error('🚨 [Services] 服务初始化失败:', error);
  });
}

/**
 * 全局错误处理设置
 */
export function setupGlobalErrorHandling(): void {
  // 检查是否在浏览器环境中
  if (typeof window === 'undefined') {
    console.warn('⚠️ [Services] 非浏览器环境，跳过全局错误处理设置');
    return;
  }

  // 导入错误处理器
  import('./errorHandler').then(({ errorHandler }) => {
    // 捕获未处理的Promise拒绝
    window.addEventListener('unhandledrejection', (event) => {
      console.error('🚨 [Global] 未处理的Promise拒绝:', event.reason);
      errorHandler.handleError(event.reason, '全局Promise错误');
      // 阻止默认的错误处理
      event.preventDefault();
    });

    // 捕获未处理的错误
    window.addEventListener('error', (event) => {
      console.error('🚨 [Global] 未处理的错误:', event.error);
      errorHandler.handleError(event.error, '全局错误');
    });

    if (process.env.NODE_ENV === 'development') {
      console.log('🛡️ [Services] 全局错误处理已设置');
    }
  }).catch(error => {
    console.error('🚨 [Services] 全局错误处理设置失败:', error);
  });
}

/**
 * 服务工具函数
 */
export const serviceUtils = {
  /**
   * 创建延迟函数
   */
  delay: (ms: number): Promise<void> => {
    if (typeof ms !== 'number' || ms < 0 || !isFinite(ms)) {
      throw new Error('延迟时间必须是非负有限数字');
    }
    return new Promise(resolve => setTimeout(resolve, ms));
  },

  /**
   * 生成随机ID
   */
  generateId: (prefix: string = 'id'): string => {
    if (typeof prefix !== 'string') {
      throw new Error('前缀必须是字符串类型');
    }
    return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
  },

  /**
   * 格式化价格
   */
  formatPrice: (price: number): string => {
    if (typeof price !== 'number' || !isFinite(price)) {
      throw new Error('价格必须是有限数字');
    }
    return `¥${price.toFixed(2)}`;
  },

  /**
   * 格式化日期
   */
  formatDate: (date: Date): string => {
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      throw new Error('输入必须是有效的Date对象');
    }
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  },

  /**
   * 验证邮箱格式
   */
  validateEmail: (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  },

  /**
   * 验证手机号格式
   */
  validatePhone: (phone: string): boolean => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  /**
   * 深拷贝对象
   */
  deepClone: <T>(obj: T): T => {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj.getTime()) as T;
    if (Array.isArray(obj)) {
      return obj.map(item => serviceUtils.deepClone(item)) as T;
    }
    
    const cloned = {} as T;
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        cloned[key] = serviceUtils.deepClone(obj[key]);
      }
    }
    
    return cloned;
  },

  /**
   * 防抖函数
   */
  debounce: <T extends (...args: any[]) => any>(
    func: T,
    delay: number
  ): ((...args: Parameters<T>) => void) & { cancel: () => void } => {
    if (typeof func !== 'function') {
      throw new Error('第一个参数必须是函数');
    }
    if (typeof delay !== 'number' || delay < 0) {
      throw new Error('延迟时间必须是非负数字');
    }
    
    let timeoutId: NodeJS.Timeout | null = null;
    
    const debouncedFn = (...args: Parameters<T>) => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(() => {
        timeoutId = null;
        func.apply(null, args);
      }, delay);
    };
    
    debouncedFn.cancel = () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
        timeoutId = null;
      }
    };
    
    return debouncedFn;
  },

  /**
   * 节流函数
   */
  throttle: <T extends (...args: any[]) => any>(
    func: T,
    delay: number
  ): ((...args: Parameters<T>) => void) & { cancel: () => void } => {
    if (typeof func !== 'function') {
      throw new Error('第一个参数必须是函数');
    }
    if (typeof delay !== 'number' || delay < 0) {
      throw new Error('延迟时间必须是非负数字');
    }
    
    let lastCall = 0;
    let timeoutId: NodeJS.Timeout | null = null;
    
    const throttledFn = (...args: Parameters<T>) => {
      const now = Date.now();
      
      if (now - lastCall >= delay) {
        lastCall = now;
        func.apply(null, args);
      } else if (!timeoutId) {
        timeoutId = setTimeout(() => {
          lastCall = Date.now();
          timeoutId = null;
          func.apply(null, args);
        }, delay - (now - lastCall));
      }
    };
    
    throttledFn.cancel = () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
        timeoutId = null;
      }
      lastCall = 0;
    };
    
    return throttledFn;
  },
};

/**
 * 服务层类型导出
 */
export * from '../types/product';

/**
 * 默认导出所有服务
 */
const services = {
  // 基础服务
  BaseService: undefined as any,
  
  // 业务服务
  ProductService: undefined as any,
  productService: undefined as any,
  SearchService: undefined as any,
  searchService: undefined as any,
  CategoryService: undefined as any,
  categoryService: undefined as any,
  
  // 工具服务
  ErrorHandler: undefined as any,
  errorHandler: undefined as any,
  InterceptorManager: undefined as any,
  interceptorManager: undefined as any,
  ApiConfigManager: undefined as any,
  apiConfigManager: undefined as any,
  apiServiceFactory: undefined as any,
  MockDataGenerator: undefined as any,
  mockDataGenerator: undefined as any,
  
  // 工具函数
  serviceUtils,
  
  // 初始化函数
  initializeServices,
  setupGlobalErrorHandling,
};

export default services;